package org.dizena.modules.wss.wsconfig;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.dizena.base.mq.RedisMQReceiver;
import org.dizena.modules.wss.bean.Message;
import org.dizena.modules.wss.service.WsService;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;


@Slf4j
@Component
public class WstHandler implements WebSocketHandler, RedisMQReceiver
{


    @Resource
    private WsService service;

    /**
     * 建立连接后
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session)
    {
        String clientId = (String) session.getAttributes().get("cid");
        service.addSocketSession(clientId, session);
        //反馈一下
        Message msgFeedback = new Message("server", clientId, "pong");
        service.sendFeedback(msgFeedback, session);
        //todo 通过 MQ 发布上线通知
        // 查看一下有没有历史消息 发给我的
        service.sendHistoryMessage(clientId, session);

    }

    /**
     * 消息处理，在客户端通过Web socket API发送的消息会经过这里，然后进行相应的处理
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
    {
        log.info("handleMessage message:{}", message.getPayload().toString());
        String clientId = (String) session.getAttributes().get("cid");
        if (message.getPayloadLength() == 0)
        {
            return;
        }
        Message msg = service.saveMessage(message);
        boolean b = service.sendMessageToUser(msg);
        if (!b)
        {
            service.convertAndSend(msg);
        }
        //反馈一下
        String content = msg.getId() + ":" + msg.getImStatus();
        Message msgFeedback = new Message("server", clientId, content);
        service.sendFeedback(msgFeedback, session);
    }

    /**
     * 消息传输错误处理
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception
    {
        log.info("error session:{} ", session.toString());
        //todo MQ通知下线
        service.removeSocketSession(session);
        if (session.isOpen())
        {
            session.close();
        }

    }

    /**
     * 关闭连接后
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
    {
        log.info("close session:{} ", session.toString());
        //todo MQ通知下线
        service.removeSocketSession(session);
    }

    @Override
    public boolean supportsPartialMessages()
    {
        return false;
    }

    @Override
    public void receiveMessage(String message)
    {
        log.info("redis mq msg:{}", message);
        Message msg = JSON.parseObject(message, Message.class);
        service.sendMessageToUser(msg);
    }


}